package com.swpu.eduservice.service.impl;

import com.swpu.eduservice.entity.Chapter.ChapterVo;
import com.swpu.eduservice.entity.Chapter.VideoVo;
import com.swpu.eduservice.entity.EduChapter;
import com.swpu.eduservice.entity.EduVideo;
import com.swpu.eduservice.mapper.EduChapterMapper;
import com.swpu.eduservice.service.EduChapterService;
import com.swpu.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author ygq
 * @since 2021-10-16
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVideoByCOurseId(String courseId) {
        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id",courseId);
        List<EduChapter> chapterList = baseMapper.selectList(chapterQueryWrapper);

        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id",courseId);
        List<EduVideo> videoList = eduVideoService.list(videoQueryWrapper);

        List<ChapterVo> res = new ArrayList<>();// 封装结果

        for (EduChapter eduChapter : chapterList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            List<VideoVo> tmp = new ArrayList<>();
            for (EduVideo eduVideo : videoList) {
                if(eduVideo.getChapterId().equals(eduChapter.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo,videoVo);
                    tmp.add(videoVo);
                }
            }
            chapterVo.setChildren(tmp);
            res.add(chapterVo);
        }
        return res;

    }

    @Override
    public boolean deleteChapter(String chapterId) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        int count = eduVideoService.count(wrapper);
        if(count>=1) return false;
        else  {
            int result = baseMapper.deleteById(chapterId);
            return result>0;

        }

    }

    @Override
    public void removeChapter(String courseId) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
     }
}
